#include "common.h"
#include "uploadlayout.h"
#include "uploadtask.h"

#include <QFileInfo>

UploadTask* UploadTask::instance = new UploadTask;
UploadTask::AutoRelease UploadTask::_at;

UploadTask *UploadTask::getInstance()
{
    return instance;
}

bool UploadTask::isEmpty()
{
    list.isEmpty();
}

bool UploadTask::isUpload()//是否有文件正在上传
{
    for(int i = 0; i < list.size(); ++i)
    {
        if(list.at(i)->isUpload == true)
        {
            return true;
        }
    }

    return false;
}

UploadFileInfo *UploadTask::takeTask()
{
    UploadFileInfo* tmp = list.at(0);
    list.at(0)->isUpload = true;

    return tmp;
}

//删除上传完成的任务
void UploadTask::dealUploadTask()
{
    for(int i = 0; i < list.size(); ++i)
    {
        if(list.at(i)->isUpload == true)
        {
            UploadFileInfo* tmp = list.takeAt(i);

            //获取布局
            UploadLayout*  pUpload = UploadLayout::getInstance();
            QLayout* layout = pUpload->getUploadLayout();
            layout->removeWidget(tmp->dp);

            QFile* file = tmp->file;
            file->close();
            delete file;

            delete tmp->dp;
            delete tmp;

            break;
        }
    }
}

void UploadTask::clearList()
{
    int n = list.size();
    for(int i = 0; i < n; ++i)
    {
        UploadFileInfo *tmp = list.takeFirst();
        delete tmp;
    }
}

int UploadTask::appendUploadList(QString path)
{
    qint64 size = QFileInfo(path).size();
//    if(size > 50*1024*1024) //50MB
//    {
//        cout << "文件太大";
//        return -1;
//    }

    for(int i = 0; i != list.size(); ++i)
    {
        if(list.at(i)->path == path)
        {
            cout << QFileInfo(path).fileName() << "已经在上传队列中";
            return -2;
        }
    }

    QFile* file = new QFile(path);

    if(!file->open(QIODevice::ReadOnly))
    {
        cout << "file open error";
        delete file;
        file = nullptr;
        return -3;
    }

    QFileInfo info(path);
    Common mc;
    UploadFileInfo* tmp = new UploadFileInfo;
    tmp->md5 = mc.getFileMd5(path);
    tmp->file = file;
    tmp->fileName = info.fileName();
    tmp->size = size;
    tmp->path = path;
    tmp->isUpload = false;

    DataProgress* p = new DataProgress;
    p->setFileName(tmp->fileName);
    tmp->dp = p;

    //获取布局
    UploadLayout* pUpload = UploadLayout::getInstance();
    if(pUpload == nullptr)
    {
        cout << "UploadTask::getInstance() == nullptr";
        return -4;
    }

    QVBoxLayout* layout = (QVBoxLayout*)pUpload->getUploadLayout();

    layout->insertWidget(layout->count()-1, p);

    cout << tmp->fileName.toUtf8().data() << "已经放在上传列表";

    list.append(tmp);
    return 0;
}
